package org.devf.fork.imsimulator.service.chat;

import org.devf.fork.imsimulator.help.MyLog;
import org.devf.fork.imsimulator.model.CurChatModel;
import org.devf.fork.imsimulator.model.UserModel;
import org.devf.fork.imsimulator.socket.dto.BasePackets;
import org.devf.fork.imsimulator.socket.dto.MsgStatus;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 内存管理聊天记录
 * DefaultMemoryChat related
 *
 * @author wanghuafu
 * @since 1.0  2023/9/22 17:01
 */
public class DefaultMemoryChat implements IChat {

    /**
     * 会话
     * key=好友关系ID || 群聊ID
     * value=聊天会话
     */
    private final Map<Long, CurChatModel> chatMap = new ConcurrentHashMap<>(20);

    @Override
    public CurChatModel getChatSession(Long chatId) {
        return chatMap.get(chatId);
    }

    @Override
    public void putChatMessage(Long key, UserModel dest, BasePackets packets) {
        CurChatModel curChatModel = chatMap.get(key);
        if (null == curChatModel) {
            curChatModel = new CurChatModel();
            curChatModel.setDestUser(dest);
            curChatModel.setSessionId(key);
            curChatModel.addPacketsTail(packets);
            chatMap.put(key, curChatModel);
        } else {
            curChatModel.addPacketsTail(packets);
        }
    }

    @Override
    public boolean updateMessageState(Long key, String packetId, MsgStatus msgStatus) {
        CurChatModel curChatModel = getChatSession(key);
        if (null == curChatModel) {
            MyLog.info("聊天消息不存在,{}", key);
            return false;
        }
        BasePackets basePackets = getPacketById(curChatModel, packetId);
        if (null != basePackets && !Objects.equals(basePackets.getMsgStatus(), msgStatus.getCode())) {
            basePackets.setMsgStatus(msgStatus.getCode());
            return true;
        }
        MyLog.info("无法匹配历史的聊天消息包,{}", key);
        return false;
    }

    /**
     * 检索消息包
     *
     * @param packetId 消息包ID
     * @return 消息包
     */
    public BasePackets getPacketById(CurChatModel curChatModel, String packetId) {
        Integer index = curChatModel.getPacketsPosition().get(packetId);
        if (null == index) {
            //todo 匹配list
            return null;
        } else {
            BasePackets basePackets = curChatModel.getHistoryList().get(index);
            if (null == basePackets) {
                //todo 匹配list
            }
            return basePackets;
        }
    }
}
